using System;
using System.IO;
using Newtonsoft.Json;

namespace ExcelTemplateEngine.Configuration
{
    public class DefaultTemplateEngineConfiguration : ITemplateEngineConfiguration
    {
        public int MaxRows { get; set; } = 1048576; // Excel最大行数
        public int MaxColumns { get; set; } = 16384; // Excel最大列数
        public bool DebugMode { get; set; } = false;
        public string TempDirectory { get; set; } = Path.GetTempPath();
        public FillMode DefaultFillMode { get; set; } = FillMode.Insert;
        public bool EnableConcurrency { get; set; } = true;
        public int MaxConcurrencyLevel { get; set; } = Environment.ProcessorCount;
        public PerformanceSettings Performance { get; set; } = new PerformanceSettings();
        
        public DefaultTemplateEngineConfiguration()
        {
            // 确保临时目录存在
            if (!Directory.Exists(TempDirectory))
            {
                Directory.CreateDirectory(TempDirectory);
            }
        }
        
        /// <summary>
        /// 验证配置的有效性
        /// </summary>
        public void Validate()
        {
            if (MaxRows <= 0)
                throw new ArgumentException("MaxRows must be greater than 0");
                
            if (MaxColumns <= 0)
                throw new ArgumentException("MaxColumns must be greater than 0");
                
            if (string.IsNullOrWhiteSpace(TempDirectory))
                throw new ArgumentException("TempDirectory cannot be null or empty");
                
            if (MaxConcurrencyLevel <= 0)
                throw new ArgumentException("MaxConcurrencyLevel must be greater than 0");
        }
        
        /// <summary>
        /// 从JSON字符串加载配置
        /// </summary>
        public static DefaultTemplateEngineConfiguration FromJson(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
                return new DefaultTemplateEngineConfiguration();
                
            try
            {
                return JsonConvert.DeserializeObject<DefaultTemplateEngineConfiguration>(json) 
                    ?? new DefaultTemplateEngineConfiguration();
            }
            catch
            {
                return new DefaultTemplateEngineConfiguration();
            }
        }
        
        /// <summary>
        /// 将配置序列化为JSON
        /// </summary>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }
    }
}